package com.example.ch2_4notification;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;

public class MainActivity extends AppCompatActivity {


    private Button btnPopup;
    private PopupMenu popupMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        btnPopup = findViewById(R.id.btn_popup);





        //创建popupmenu对象
        popupMenu = new PopupMenu(this, btnPopup);
        //加载菜单资源，并关联给popupmenu的菜单
        popupMenu.getMenuInflater().inflate(
                R.menu.file_menu, //菜单资源
                popupMenu.getMenu()//关联
        );
        //注册菜单项点击事件监听器
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuitem) {
                //判断当前选择的是哪一个菜单选项
                switch (menuitem.getItemId()){
                    case R.id.menu_file:
                        //日志记录选择的菜单项
                        Log.i("msg","文件");
                        break;
                    case R.id.menu_file_open:
                        Log.i("msg","文件-打开 菜单");
                        break;
                    case R.id.menu_file_save:
                        Log.i("msg","文件-另存为 菜单");
                        break;
                }
                return true;
            }
        });

        //显示菜单（通常在特定事件下触发）
        btnPopup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //弹出式菜单
                popupMenu.show();

            }
        });



    }




    //加载菜单资源开关并关联给activity默认的选项菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //1.使用菜单资源加载器加载菜单资源

        //2.把菜单资源关联给activity，默认的选项菜单
        getMenuInflater().inflate(R.menu.file_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    //给选项菜单注册item选择事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        //判断当前选择的是哪一个菜单选项
        switch (item.getItemId()){
            case R.id.menu_file:
                //日志记录选择的菜单项
                Log.i("msg","文件");
                break;
            case R.id.menu_file_open:
                Log.i("msg","文件-打开 菜单");
                break;
            case R.id.menu_file_save:
                Log.i("msg","文件-另存为 菜单");
                break;
        }

        return super.onOptionsItemSelected(item);
    }


}